use leptos::{
    ev::{self, MouseEvent},
    prelude::*,
};

#[derive(Debug, Clone, Copy)]
pub enum Direction {
    Horizontal,
    Vertical,
}

#[component]
pub fn PaneExpander(
    expand: RwSignal<bool>,
    #[prop(optional, into)] class: MaybeProp<String>,
    #[prop(default = Direction::Horizontal)] direction: Direction,
) -> impl IntoView {
    let (is_resizing, set_is_resizing) = signal(false);
    let (client_position, set_client_position) = signal(0);
    let start_resize = move |event: MouseEvent| {
        event.prevent_default();
        set_is_resizing.set(true);
        match direction {
            Direction::Horizontal => {
                set_client_position.set(event.client_x());
            }
            Direction::Vertical => {
                set_client_position.set(event.client_y());
            }
        }
    };
    let mousemove_listener = window_event_listener(ev::mousemove, move |event| {
        if is_resizing.get() {
            let new_client_position = match direction {
                Direction::Horizontal => event.client_x(),
                Direction::Vertical => event.client_y(),
            };
            if new_client_position - client_position.get() > 5 {
                expand.set(true);
                return;
            }
            if new_client_position - client_position.get() < 5 {
                expand.set(false);
            }
        }
    });
    let mouseup_listener = window_event_listener(ev::mouseup, move |_| {
        set_is_resizing.set(false);
    });
    on_cleanup(move || {
        mousemove_listener.remove();
        mouseup_listener.remove();
    });
    view! { <div class=move || class.get() on:mousedown=start_resize /> }
}
